package sms_interface;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;
/**
 * 
 * @author aayushjain
 * This class detects whether their is any electricity wastage in the room and sends message accordingly.
 */
public class Electricity_wastage {
	
	/**
	 * Whenever the sensor information indicates that some electricity is being wasted, sms is send to the concerned authority.
	 * @throws Exception
	 */
	public static void wastage() throws Exception
	{
		while(true)
		{
	
		String Url = "jdbc:mysql://localhost:3306/data";
		String query = "Select * FROM data_table Limit ";
		Random ran=new Random();
		int num=ran.nextInt(5000);
		//System.out.println(num);
		query=query+num+",1000";
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection (Url,"root","aayush");
		Statement stmt = con.createStatement();
		ResultSet rs2= stmt.executeQuery(query);
		int count=0;
		int flag=0;
		int count2=0;
		double threstemp=27;
		while(rs2.next())
		{
			int Msense=rs2.getInt(2);
			int Dsense=rs2.getInt(3);
			int Wsense=rs2.getInt(4);
			double temp=rs2.getDouble(5);
			//System.out.println(Dsense+" " +Wsense+" "+ temp);
			//System.out.println(Msense+" "+ temp);
			
			if( (Dsense==1 || Wsense==1) && (temp>10 &&temp<threstemp)  )
			{
				//System.out.println("abc");
				count++;
				if( count>20)
				{
					System.out.println("Electricity wastage detected.");
					flag=1;
					break;					
				}
			}
			else
			{
				count=0;
			}
		
			if( (Msense==0) && ((temp>10) && (temp<threstemp)) )
			{
				
				count2++;
				if( count2>20)
				{
					//System.out.println("Electricity wastage detected.");
					flag=1;
					break;					
				}
			}
			else
			{
				count2=0;
			}
		
		}
		//System.out.println(count);
		if(flag==1){
			Sending_sms_mysql.get_authority("cr1", "f1");
		}
		Thread.sleep(5000);
		System.out.println("abcd");
		}
	}
	
	/**
	 * Runs the server which detects electricity wastage.
	 * @param args
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception{
		wastage();
	}
}
